package org.domeos.framework.api.controller.auth;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang.StringUtils;
import org.domeos.basemodel.HttpResponseTemp;
import org.domeos.basemodel.ResultStat;
import org.domeos.framework.api.consolemodel.auth.UserPassword;
import org.domeos.framework.api.model.auth.User;
import org.domeos.framework.api.service.auth.UserService;
import org.domeos.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * SRE登录接口对接
 * @author haqiaolong
 *
 */
@Controller
@RequestMapping("/sre/api")
@Api("SRE部署相关API")
@PropertySource("application.properties")
public class LoginSreController {

	protected static Logger logger = LoggerFactory.getLogger(LoginSreController.class);
	private static final String TOKEN_KEY = "gdocker-api-user";
	@Autowired
	UserService  userService;
	@Autowired
    StringRedisTemplate stringRedisTemplate;
	
	@Value("${idcenter.url}") String url;
	
	@ApiOperation(value="登录")
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public HttpResponseTemp<?> normalLogin(@RequestBody UserPassword userPassword) {
		if(userPassword == null){
			return ResultStat.PARAM_ERROR.wrap("userPassword name is null!");
		}
		if(StringUtils.isEmpty(userPassword.getUsername())
				|| StringUtils.isEmpty(userPassword.getPassword())){
			return ResultStat.PARAM_ERROR.wrap("userPassword name is null!");
		}
		boolean result = idCenterLogin(userPassword);
		if(result){ //登录成功
			User user =  userService.getUser(userPassword.getUsername());
			if(user == null){
				user = new User(userPassword.getUsername(), "11111111");
				user.setEmail(userPassword.getUsername());
				userService.createUser(user,false);
			}
			String token = HmacUtils.hmacMd5Hex(TOKEN_KEY, user.getId() + userPassword.getPassword());
			String value = stringRedisTemplate.opsForValue().get(token);
			if(StringUtils.isEmpty(value)){
				stringRedisTemplate.opsForValue().set(token, user.getId() + "");
				stringRedisTemplate.expire(token, 2, TimeUnit.HOURS);
			}else{
				stringRedisTemplate.expire(token, 2, TimeUnit.HOURS);
			}
	        logger.info("idcenter login success, user=" + userPassword.getUsername());
	        return ResultStat.OK.wrap(token);
		}
		return ResultStat.SERVER_INTERNAL_ERROR.wrap("登陆失败！");
    }
	
	/**
	 * 架构部IDCENTER登录
	 * @param userPassword
	 * @return
	 */
	private boolean idCenterLogin(UserPassword userPassword){
		Map<String,Object> params = new HashMap<>();
		params.put("userName", userPassword.getUsername());
		params.put("passwd", userPassword.getPassword());
		String result = HttpClientUtil.doPost(url, params);
		return StringUtils.equalsIgnoreCase(result, "0");
	}
}
